//
//  SearchVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/18.
//

import UIKit

@available(iOS 13.0, *)
class SearchVC: BaseVC,UISearchBarDelegate {

        
    var searchBar = UISearchBar()
        var users =  [DMCCUser]()
        var groups = [DMCCGroup]()

        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            navigationController?.setNavigationBarHidden(true, animated: animated)
            
        }

        override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(animated)
            navigationController?.setNavigationBarHidden(false, animated: animated)
        }

        override func viewDidLoad() {
            super.viewDidLoad()
            
            searchBar.frame = CGRect(x: 0, y: iPhoneXNavStatus, width: kScreenWidth, height: 60)
            searchBar.placeholder = KLocalizedString("PleaseEnterSearch")
            searchBar.barTintColor = UIColor.white
            searchBar.searchBarStyle = .minimal
            self.view.addSubview(searchBar)
            tableStytle = .grouped
            tableView.separatorInset = UIEdgeInsets(top: 0, left: 76, bottom: 0, right: 0)
            
//            searchBar.becomeFirstResponder()
            
            tableView.frame = CGRect(x: 0, y: CGFloat(60 + iPhoneXNavStatus), width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - CGFloat((60 + iPhoneXNavStatus)))
            registerCell(withNibName: String(describing: UserCell.self), isTableView: true)
//            registerCell(withNibName: String(describing: MHHYContactGroupCell.self), isTableView: true)
//            registerHeaderFooter(withNibName: String(describing: MHHYContactHead.self))
            
//            if #available(iOS 9.0, *) {
//                UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.MainColor, for: .normal)
//            } else {
//                UIBarButtonItem.appearance(whenContainedIn: UISearchBar.self, nil).setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .normal)
//            }
            navigationController?.interactivePopGestureRecognizer?.delegate = false as? any UIGestureRecognizerDelegate
            searchBar.delegate = self
            getData()
        }
        
    override func getData() {
            if (users.isEmpty) &&  groups.isEmpty {
                self.view.insertSubview(self.nullView, aboveSubview: self.view)
            } else {
                self.nullView.removeFromSuperview()
            }
        }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return users.count
        }
        return groups.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            if indexPath.section == 0 {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UserCell.self)) as? UserCell else { return UITableViewCell() }
                cell.setUserInfo(userInfo: users[indexPath.row])
                return cell
            } else {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UserCell.self)) as? UserCell else { return UITableViewCell() }
//                let groupInfo = groups[indexPath.row] as? GroupInfo
//                cell.icon.sd_setImage(with: URL(string: groupInfo.getPortrait()), placeholderImage: SDImageDefault)
//                cell.nickName.text = groupInfo.name
                cell.setGroup(group: groups[indexPath.row])
                return cell
            }
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            tableView.deselectRow(at: indexPath, animated: true)
            if indexPath.section == 0 {
                let user = users[indexPath.row]
                navigationController?.pushViewController(UserDetailVC(userInfo: user), animated: true)
            } else {
//                guard let groupInfo = groups?[indexPath.row] as? GroupInfo else { return }
//                let conversation = ConversationInfo.init(withParam: groupInfo.groupId, type: Group_Type)
//                navigationController?.pushViewController(MHHYSingleChatVC(conversationInfo: conversation), animated: true)
            }
        }

        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            if section == 0 {
                return users.count > 0 ? 30.0 : 0.001
            }else{
                return groups.count > 0 ? 30.0 : 0.001
            }
        }

        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

            
            let head = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 30))
//            head.backgroundColor = UIColor.white
            if users.count > 0 {
                let lab = UILabel(frame: CGRect(x: 16, y: 0, width: 100, height: 30))
                lab.font = UIFont.systemFont(ofSize: 14)
                if section == 0 {
                    lab.text = "好友"
                }
                head.addSubview(lab)
            }
            
            if groups.count > 0 {
                let lab = UILabel(frame: CGRect(x: 14, y: 0, width: 100, height: 30))
                if section == 1 {
                    lab.text = "群聊"
                }
                head.addSubview(lab)
            }
            
//            head.titleLab.text = section == 0 ? KLocalizedString("user") : KLocalizedString("Group")
//            head.titleLab.font = UIFont.systemFont(ofSize: 12)
//            head.contentView.backgroundColor = FontManage.MHLineSeparatorColor()
            
            
            return head
        }

        func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
            let view = UIView()
//            view.backgroundColor = FontManage.MHLineSeparatorColor()
            return view
        }

        func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
            return 0.001
        }

        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 70
        }



        // UISearchBarDelegate
        func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
            searchBar.showsCancelButton = true
            searchBar.setShowsCancelButton(true, animated: true)
        }

        func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
            serarchWithStr(searchBar.text ?? "")
        }

        func serarchWithStr(_ str: String) {
            let searchStr = str.trimmingCharacters(in: .whitespacesAndNewlines)
            if searchStr.isEmpty {
                MHAlert.showMessage(KLocalizedString("PleaseEnterSearch"))
                return
            }
//            let ws = self as! MHHYSearchVC
            
//            DMCCIMService.getInstance().searchUser(str, search: 0, page: 0) { users in
//                ws.users = machedUsers
//                ws.getData()
//                ws.tableView.reloadData()
//            } error: { e in
//                
//            }

            self.users = gosnMessage.searchUser(str)
            self.groups = gosnMessage.searchGroup(str)
            getData()
            self.tableView.reloadData()
            
//            DMCCIMService.getInstance().searchUser(str, search: DMCCSearchUserType(rawValue: 0)!, page: 0) { [weak self] machedUsers in
//                self!.users = machedUsers!
//                self!.getData()
//                self!.tableView.reloadData()
//            } error: {  errorCode in
//                // Handle error
//            }
//
//            DMCCIMService.getInstance().searchGroup(str, page: 0) { [weak self] machedGroups in
//                self!.groups = machedGroups!
//                self!.getData()
//                self!.tableView.reloadData()
//            } error: {  errorCode in
//                // Handle error
//            }
        }

        func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
            dismiss()
        }

    }
